const router = require("koa-router")()
router.prefix("/admin")
var { Goods, GoodsMain, GoodsGuide, GoodsFirstClass, GoodsSecondClass } = require("../models/goods")

// 上传配置项

var upload = require("../models/multer").upload

const fs = require("fs")
const FilePath = "/public/uploads"
const ReadAllImage = require("../models/multer").ReadAllImage

//  删除图片

var unlink = require("../models/multer").unlink

var CtxBody = require("../models/config").CtxBody

var URL = require("../models/config").ServerUrl

// 每页数据个数

const PageSize = require("../models/config").PageSize

// 图片上传中间件

var upload = require("../models/multer").upload

// 添加商品主图

router.post("/addGoodsMain", upload.array("main", 5), async ctx => {
    console.log(ctx.req.files);
    let main = ctx.req.files
    
    arr = main.map(el => {
        if (el.filename) {
            return `${URL}/public/uploads/${el.filename}`
        }
    });
    CtxBody(ctx, 202, arr)
})

// 添加商品详情页

router.post("/addGoodsImgList", upload.array("imglist", 15), async ctx => {
    
    let imglist = ctx.req.files
    
    arr = imglist.map(el => {
        if (el.filename) {
            return `${URL}/public/uploads/${el.filename}`
        }
    });
    CtxBody(ctx, 202, arr)
})

// 添加规格

router.post("/addGoods", async ctx => {
    let { title, stock, price, sale, proportion, secproportion, guides, beLong, mainImage, ImageList , id } = ctx.request.body
    // console.log( ctx.request.body.title );
    
    if (id) {
        let good = await Goods.findOneAndUpdate({ _id: id }, {
            $set: {
                title,
                price,
                stock,
                sale,
                proportion,
                secproportion,
                beLong,
                guides,
                mainImage,
                ImageList
            }
        })
        CtxBody(ctx, 204, good)
    } else {
        if (title && stock && price ) {
            let newGoods = new Goods({
                title,
                price,
                stock,
                sale,
                proportion,
                secproportion,
                beLong,
                guides,
                mainImage,
                ImageList
            })
    
            let saveGoods = await newGoods.save()
            CtxBody(ctx, 202, saveGoods)
        }
    }
    
})

// 根据ID查找商品

router.post("/findGoodsByID", async ctx => {
    let { id } = ctx.request.body
    if (id) {
        let allGoods = await Goods.findOne({ _id: id })
        if (allGoods) {
            CtxBody(ctx, 200, allGoods)
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 后台查看所有商品

router.post("/ShowAllGoods", async ctx => {
    
    let { page , goodsClass } = ctx.request.body
    let SkipPage = page ? page : 1
    let total = await Goods.count()
    if (goodsClass) {
        let cls = await GoodsSecondClass.findOne({ _id: goodsClass })
        let goods = await Goods.find({"beLong.classname": cls.classname })
        let total = goods.length ? goods.length : 0
        let goodsList = goods.slice( (SkipPage - 1 ) * PageSize, SkipPage * PageSize )
        CtxBody(ctx, 200, { goodsList, total})
    } else {
        let allGoods = await Goods.find({}, "_id mainImage title price sale proportion secproportion status addtime").skip( (SkipPage - 1) * PageSize ).limit(PageSize)
        if (allGoods.length > 0) {
            CtxBody(ctx, 200, {allGoods, total})
        } else {
            CtxBody(ctx, 404, "")
        }
    }
})

// 商品是否显示

router.post("/goodsStatusChange", async ctx => {
    let { id } = ctx.request.body 
    let goods = await Goods.findOne({ _id: id })
    if (goods.status == 1) {
        let update = await Goods.findOneAndUpdate({ _id: id }, { $set: { status: "2" }})
        CtxBody(ctx, 204, "")
    } else {
        let update = await Goods.findOneAndUpdate({ _id: id }, { $set: { status: "1" }})
        CtxBody(ctx, 204, "")
    }
})

// 根据二级类目查找商品

router.post("/findGoodsBySecondClass", async ctx => {
    let { secondName, page } = ctx.request.body
    let SkipPage = page ? page : 1
    let allCount = await Goods.find({ beLong: secondName })
    let allGoods = await Goods.find({ beLong: secondName }, "_id title stock status price sale proportion secproportion mainImage").skip((SkipPage - 1) * PageSize).limit( PageSize )
    let total = allCount.length
    if (allCount && allGoods) {
        CtxBody(ctx, 200, { allGoods, total})
    } else {
        CtxBody(ctx, 404, "")
    }
    
})


// 添加或修改一 二级类目 有图片

router.post("/addClassWithIcon", upload.single("icons") ,  async ctx => {
    let { classname, id, fid, icon, status } = ctx.req.body
    let filename = ctx.req.file.filename
    if (fid) {
        if (id) {
            let isok = await unlink( icon.replace(`${URL}/public/uploads/`, ""))
            let sec = await GoodsSecondClass.findOneAndUpdate({ _id: id }, {
                $set: {
                    classname,
                    icon: `${URL}/public/uploads/${filename}`,
                    status
                }
            }, { new: true })
            CtxBody(ctx, 204, "")
        } else {
            let second = new GoodsSecondClass({
                classname,
                beLong:fid,
                icon: `${URL}/public/uploads/${filename}`,
                status
            })
            let res = await second.save()
            let update = await GoodsFirstClass.findOneAndUpdate({ _id: fid } , {
                $push: {
                    children: res._id
                }
            } )
            CtxBody(ctx, 204, "")
        }
    } else {
        if (id) {
            console.log(1);
            let file = icon.replace(`${URL}/public/uploads/`,"")
            console.log(file);
            
            let isok = await unlink( file )
            console.log(isok);
            
            let clas = await GoodsFirstClass.findOneAndUpdate({ _id: id}, {
                $set: {
                    classname,
                    icon: `${URL}/public/uploads/${filename}`,
                    status
                }
            }, { new: true })
            CtxBody(ctx, 204, "")
        } else {
                let hasClass = await GoodsFirstClass.findOne({ classname })
                if (hasClass) {
                    CtxBody(ctx, 402, "")
                } else {
                    let newClass = new GoodsFirstClass({
                        classname,
                        icon: `${URL}/public/uploads/${filename}`,
                        status
                    })
                    let res = await newClass.save()
                    CtxBody(ctx, 202, "")
                }
          
        }
    }
})

// 添加或修改一 二级类目 没有 图片

router.post("/addClass",  async ctx => {
    let { classname, id, fid, status } = ctx.request.body
    if (fid) {
        if (id) {
            let sec = await GoodsSecondClass.findOneAndUpdate({ _id: id }, {
                $set: {
                    classname,
                    status 
                }
            }, { new: true })
            CtxBody(ctx, 204, "")
        } else {
            let second = new GoodsSecondClass({
                classname,
                beLong:fid,
                status
            })
            let res = await second.save()
            let update = await GoodsFirstClass.findOneAndUpdate({ _id: fid } , {
                $push: {
                    children: res._id
                }
            } )
            CtxBody(ctx, 204, "")
        }
    } else {
        if (id) {
            let clas = await GoodsFirstClass.findOneAndUpdate({ _id: id}, {
                $set: {
                    classname,
                    status
                }
            }, { new: true })
            CtxBody(ctx, 204, "")
        } else {
            
                let hasClass = await GoodsFirstClass.findOne({ classname })
                if (hasClass) {
                    CtxBody(ctx, 402, "")
                } else {
                    let newClass = new GoodsFirstClass({
                        classname,
                        status
                    })
                    let res = await newClass.save()
                    CtxBody(ctx, 202, "")
                }
          
        }
    }
})

// 删除一级类目

router.post("/deleteClass", async ctx => {
    let { id, fid } = ctx.request.body
    if (fid) {
        let sec = await GoodsSecondClass.findOneAndDelete({ _id: id })
        CtxBody(ctx, 204, "")
    } else {
        if (id) {
            let child = await GoodsFirstClass.findOne({_id: id})
            let clas = await GoodsFirstClass.findOneAndDelete({ _id: id }, { new: true })
            child.children.forEach( async el => {
                let sec = await GoodsSecondClass.findOneAndDelete({ _id: el })
            });
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 30003, "")
        }
    }
})




// 后台展示一级和二级类目

router.post("/ShowClass", async ctx => {
    let { page } = ctx.request.body 
    let SkipPage = page ? page : 1
    let total = await GoodsFirstClass.count()
    let clas = await GoodsFirstClass.find().skip(( SkipPage - 1 ) * PageSize).limit( PageSize ).populate({ path: "children", select: "_id classname icon beLong status"})
    if (clas.length > 0) {

        CtxBody(ctx, 200, {clas, total})
    } else {

        CtxBody(ctx, 404, "")
    }
})

// 后台一级和二级类目 更改状态

router.post("/GoodsClassStatusChange", async ctx => {
    let { id,beLong } = ctx.request.body 

    if (!beLong) {
        console.log(1);
        let res = await GoodsFirstClass.findOne({ _id: id })
        // res存在 说明是一级目录
        if (res.status == 1) {
            let update = await GoodsFirstClass.findOneAndUpdate({ _id: id }, { $set: { status: "2" }}, {new: true})
            CtxBody(ctx, 204, "")
        } else {
            let update = await GoodsFirstClass.findOneAndUpdate({ _id: id }, { $set: { status: "1" }}, {new: true})
            CtxBody(ctx, 204, "")
        }
    } else {
        console.log(2);
        let sec = await GoodsSecondClass.findOne( { _id: id })
        console.log(sec);
        
        if (sec.status == 1) {
            console.log(3);
            let update = await GoodsSecondClass.findOneAndUpdate({ _id: id }, { $set: { status: "2" }}, {new: true})
            CtxBody(ctx, 204, "")
        } else {
            console.log(4);
            let update = await GoodsSecondClass.findOneAndUpdate({ _id: id }, { $set: { status: "1" }}, {new: true})
            CtxBody(ctx, 204, "")
        }
    }
})


// 读取目录中所有的图片

router.post("/allImage", async ctx => {
    let { page } = ctx.request.body
    let SkipPage = page ? page : 1
    
    let all = await ReadAllImage()
    
   if (all.length > 0) {
        let count = all.length 
       let res = all.slice( (SkipPage - 1 ) * PageSize , SkipPage * PageSize )
       CtxBody(ctx, 200, {res, count})
   } else {
       CtxBody(ctx, 202, { data: [] , count : 0})
   }
    
})

module.exports = router